package org.ccheng.gui.userInfo;

import cn.hutool.core.date.DateUtil;
import de.felixroske.jfxsupport.FXMLController;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import org.ccheng.common.BeanUtil;
import org.ccheng.xztx.domain.UserInfo;
import org.ccheng.xztx.scheduler.Scheduler;
import org.ccheng.xztx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

@FXMLController
public class UserInfoCtrl implements Initializable {

    @Autowired
    private UserService userService;

    @FXML
    private GridPane userInfoPane;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        updateUserInfo();
    }

    public void updateUserInfo() {

        Scheduler.userInfoObservable
                .observeOn(JavaFxScheduler.platform())
                .subscribe(next -> {
                    UserInfo userInfo = userService.findById(null);

                    userInfoPane.getChildren().clear();

                    List<Map<String, String>> maps = BeanUtil.getAttribute(userInfo, UserInfo.class);
                    int i = 0;
                    for (i = 0; i < maps.size(); i++) {
                        Map<String, String> map = maps.get(i);

                        Label label = new Label(map.get("key"));
                        userInfoPane.setColumnIndex(label, 0);
                        userInfoPane.setRowIndex(label, i);
                        userInfoPane.getChildren().add(label);

                        Label valueLabel = new Label(map.get("value"));
                        userInfoPane.setColumnIndex(valueLabel, 1);
                        userInfoPane.setRowIndex(valueLabel, i);
                        userInfoPane.getChildren().add(valueLabel);
                    }

                    // 用户信息最后刷新时间
                    Label label = new Label("最后刷新时间");
                    userInfoPane.setColumnIndex(label, 0);
                    userInfoPane.setRowIndex(label, i++);
                    userInfoPane.getChildren().add(label);

                    Label valueLabel = new Label(DateUtil.format(DateUtil.date(), "HH:mm:ss"));
                    userInfoPane.setColumnIndex(valueLabel, 0);
                    userInfoPane.setRowIndex(valueLabel, i++);
                    userInfoPane.getChildren().add(valueLabel);

                });

    }
}
